﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace FootSteps.Domain.Loggers.Keyboard
{
    public class KeyboardInterceptor : DG.Common.Patterns.MVVM.ViewModelBase
    {
        #region locals

        // ReSharper disable InconsistentNaming
        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        // ReSharper restore InconsistentNaming


        private LowLevelKeyboardProc _proc;
        private IntPtr _hookID = IntPtr.Zero;
        private bool _started;

        #endregion

        public delegate void KeyDownHandler(KeyArgs e);
        public event KeyDownHandler OnKeyDown;

        public KeyboardInterceptor()
        {
            _proc = HookCallback;
        }

        public bool Started
        {
            get { return _started; }
            set
            {
                if (value.Equals(_started)) return;
                _started = value;
                OnPropertyChanged("Started");
            }
        }

        public void Start()
        {
            if (Started) return;
            Started = true;
            _hookID = SetHook(_proc);
        }
        public void Stop()
        {
            if (!Started) return;
            Started = false;

            UnhookWindowsHookEx(_hookID);
        }

        private IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (var curProcess = Process.GetCurrentProcess())
            using (var curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

        private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
            {
                var vkCode = Marshal.ReadInt32(lParam);
                var keys = (Keys)vkCode;

                RaiseKeyDown(keys);
            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }

        private void RaiseKeyDown(Keys keys)
        {
            if (OnKeyDown != null) OnKeyDown(new KeyArgs(keys, DateTime.Now));
        }

        #region P/Invoke

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod,uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern short GetKeyState(int nVirtKey);
        #endregion

    }
}